﻿using FluentValidation;
using FluentValidation.Validators;
using PMS.Data.Entities.Settings;
using System.Text.RegularExpressions;

namespace PMS.Web.Framework.Validators
{
    /// <summary>
    /// Phohe number validator
    /// </summary>
    public class MobilePhoneValidator<T, TProperty> : PropertyValidator<T, TProperty>
    {
        public override string Name => "MobilePhoneValidator";
        private readonly CustomerSettings _customerSettings;

        /// <summary>
        /// Ctor
        /// </summary>
        public MobilePhoneValidator(CustomerSettings customerSettings)
        {
            _customerSettings = customerSettings;
        }
        protected override string GetDefaultMessageTemplate(string errorCode)
                            => ValidatorRuleString.Validators_MobilePhone;
        /// <summary>
        /// Is valid?
        /// </summary>
        /// <param name="context">Validation context</param>
        /// <returns>Result</returns>
        public override bool IsValid(ValidationContext<T> context, TProperty value)
        {
            return IsValid(value as string, _customerSettings);
        }

        /// <summary>
        /// Is valid?
        /// </summary>
        /// <param name="phoneNumber">Phone number</param>
        /// <param name="customerSettings">Customer settings</param>
        /// <returns>Result</returns>
        public static bool IsValid(string phoneNumber, CustomerSettings customerSettings)
        {
            if (!customerSettings.PhoneNumberValidationEnabled || string.IsNullOrEmpty(customerSettings.PhoneNumberValidationRule))
                return true;

            if (string.IsNullOrEmpty(phoneNumber))
                return false;

            return Regex.IsMatch(phoneNumber, customerSettings.PhoneNumberValidationRule, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
        }
    }

}
